#include "networkscan.h"
#include <QHostInfo>
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QTimer>
#include "machineutil.h"
#include "mylogger.h"

using namespace ns_yht;

namespace
{
    const QString SERVER = "iotdevice.ehanghai.cn" /* "47.98.199.227"*/;
    const QString SERVER_DEVELOP = "192.168.18.126";
}

NetworkScan::NetworkScan()
{
    m_isScanning = false;

    removeOldFiles();
    if (GLOG)
        GLOG->info("NetworkScanThread construct...  deviceSerial:{}", MachineUtil::machineCode().toStdString());
}

NetworkScan::~NetworkScan()
{
    if (m_timer)
        delete m_timer;
    if (GLOG)
        GLOG->info("NetworkScanThread destruct...");
}

void NetworkScan::run()
{
    if (m_timer == nullptr)
    {
        m_timer = new QTimer;
        connect(m_timer, &QTimer::timeout, this, &NetworkScan::scan);
        scan();
        m_timer->start(30000);
    }
}

void NetworkScan::scan()
{
    if (m_isScanning)
        return;
    m_isScanning = true;
    GLOG->debug("start networkScan......");
#if 1
    // 该方式在使用IP地址做参数时往往返回通，即使明明是断开的
    QHostInfo::lookupHost(MyLogger::developDebug ? SERVER_DEVELOP : SERVER, this, SLOT(slot_lookup(QHostInfo)));
#else // 这个也有问题，有时明明是通的却说不通
    QString result;
    if (!network_process)
        network_process = new QProcess(); // 不要加this
    network_process->start("ping", QStringList() << DATAPOSTBACK->getServer() << "-n" << "2" << "-w" << "500", QIODevice::ReadOnly);
    network_process->waitForFinished();                     // 等待指令执行完毕
    result = network_process->readAll();                    // 获取指令执行结果
    if (result.contains("ttl=") || result.contains("TTL=")) // 若包含TTL=字符串则认为网络在线
    {
        if (m_status != 1)
        {
            m_status = 1;
            emit statusChanged(true);
            tokenScan();
        }
    }
    else
    {
        if (m_status != 0)
        {
            m_status = 0;
            emit statusChanged(false);
        }
    }
    emit statusRefreshed(m_status);
    m_isScanning = false;
    GLOG->info("NetworkStatus ======== {}", m_status);
#endif
}

void NetworkScan::slot_lookup(QHostInfo host)
{
    if (host.error() != QHostInfo::NoError)
    {
        if (m_status != 0)
        {
            m_status = 0;
            emit statusChanged(false);
        }
    }
    else
    {
        if (m_status != 1)
        {
            m_status = 1;
            emit statusChanged(true);
        }
    }
    emit statusRefreshed(m_status);
    m_isScanning = false;

    if (GLOG)
        GLOG->info("NetworkStatus ======== {}", m_status);
}

void NetworkScan::removeOldFiles()
{
    // 调整更新程序后，启动主程序，删除.old文件
    QStringList dirList;
    const QString cdir = QCoreApplication::applicationDirPath();
    dirList.append(cdir);
#ifdef __linux__
    dirList.append(cdir + "/../lib/");
#else
    dirList.append(cdir + "/audio/");
    dirList.append(cdir + "/bearer/");
    dirList.append(cdir + "/iconengines/");
    dirList.append(cdir + "/imageformats/");
    dirList.append(cdir + "/mediaservice/");
    dirList.append(cdir + "/platforms/");
    dirList.append(cdir + "/playlistformats/");
    dirList.append(cdir + "/position/");
    dirList.append(cdir + "/printsupport/");
    dirList.append(cdir + "/sqldrivers/");
    dirList.append(cdir + "/styles/");
#endif

    foreach (auto &d, dirList)
    {
        QDir dir(d);
        if (!dir.exists())
            continue;
        QStringList fileList = dir.entryList({"*.old"});
        foreach (auto &f, fileList)
        {
            QFile::remove(d + "/" + f);
        }
    }
}

void NetworkScan::stop()
{
    m_timer->stop();
    m_timer->deleteLater();
    m_timer = nullptr;
}
